﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlsugarService.Application.AI.KouZi_AI;
using SqlsugarService.Application.AI.KouZi_AI.Dtos;
using System.ComponentModel.DataAnnotations;

namespace SqlsugarService.API.Controllers
{
    /// <summary>
    /// 扣子AI智能体控制器
    /// 
    /// 提供与扣子AI平台交互的RESTful API接口，包括：
    /// - 发送消息给AI智能体（支持流式和非流式）
    /// - 查询聊天记录和会话状态
    /// - 提交工具执行结果
    /// - 健康检查和服务状态监控
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class KouziAIController : ControllerBase
    {
        private readonly IKouZiAIService _kouziAIService;
        private readonly ILogger<KouziAIController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="kouziAIService">扣子AI服务接口</param>
        /// <param name="logger">日志记录器</param>
        public KouziAIController(IKouZiAIService kouziAIService, ILogger<KouziAIController> logger)
        {
            _kouziAIService = kouziAIService ?? throw new ArgumentNullException(nameof(kouziAIService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 发送消息给扣子AI智能体（非流式响应）
        /// </summary>
        /// <param name="request">请求参数，包含消息内容、用户ID、智能体配置等</param>
        /// <returns>智能体的完整响应结果</returns>
        /// <response code="200">请求成功，返回AI响应结果</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("send-message")]
        [ProducesResponseType(typeof(KouZiAIResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<KouZiAIResponseDto>> SendMessageAsync([FromBody] KouZiAIRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到发送消息请求，内容长度: {request.Content?.Length ?? 0}");

                var result = await _kouziAIService.SendMessageAsync(request);

                if (result.Success)
                {
                    _logger.LogInformation($"消息发送成功，会话ID: {result.ConversationId}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"消息发送失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 发送消息给扣子AI智能体（流式响应）
        /// </summary>
        /// <param name="request">请求参数，自动设置为流式模式</param>
        /// <returns>包含所有流式响应事件的列表</returns>
        /// <response code="200">请求成功，返回流式响应事件列表</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("send-stream-message")]
        [ProducesResponseType(typeof(List<KouZiAIStreamResponseDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<List<KouZiAIStreamResponseDto>>> SendStreamMessageAsync([FromBody] KouZiAIRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到流式消息请求，内容长度: {request.Content?.Length ?? 0}");

                var result = await _kouziAIService.SendStreamMessageAsync(request);

                _logger.LogInformation($"流式消息处理完成，事件数量: {result.Count}");
                return Ok(result);
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送流式消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 发送消息给扣子AI智能体（流式响应，返回合并内容）
        /// </summary>
        /// <param name="request">请求参数，内部会自动设置为流式模式</param>
        /// <returns>合并后的完整响应内容</returns>
        /// <response code="200">请求成功，返回合并后的完整回复</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("send-stream-merged")]
        [ProducesResponseType(typeof(KouZiAIResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<KouZiAIResponseDto>> SendStreamMergedAsync([FromBody] KouZiAIRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到流式合并消息请求，内容长度: {request.Content?.Length ?? 0}");

                var result = await _kouziAIService.SendStreamMergedAsync(request);

                if (result.Success)
                {
                    _logger.LogInformation($"流式合并消息处理成功，会话ID: {result.ConversationId}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"流式合并消息处理失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送流式合并消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 快速发送消息（使用默认配置）
        /// </summary>
        /// <param name="content">要发送的消息内容，不能为空</param>
        /// <param name="userId">用户ID，可选，默认为"123456"</param>
        /// <returns>智能体的响应结果</returns>
        /// <response code="200">请求成功，返回AI响应结果</response>
        /// <response code="400">消息内容为空</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("quick-send")]
        [ProducesResponseType(typeof(KouZiAIResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<KouZiAIResponseDto>> QuickSendAsync(
            [FromBody, Required] string content, 
            [FromQuery] string? userId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(content))
                {
                    return BadRequest(new { error = "消息内容不能为空" });
                }

                _logger.LogInformation($"收到快速发送请求，内容长度: {content.Length}");

                var result = await _kouziAIService.QuickSendAsync(content, userId);

                if (result.Success)
                {
                    _logger.LogInformation($"快速发送成功，会话ID: {result.ConversationId}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"快速发送失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError(ex, "消息内容为空");
                return BadRequest(new { error = "消息内容不能为空" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "快速发送消息时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 查询聊天记录
        /// </summary>
        /// <param name="chatId">聊天ID</param>
        /// <param name="conversationId">会话ID</param>
        /// <returns>包含聊天记录详情的响应对象</returns>
        /// <response code="200">查询成功，返回聊天记录详情</response>
        /// <response code="400">参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("retrieve-chat")]
        [ProducesResponseType(typeof(ChatRetrieveResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ChatRetrieveResponseDto>> RetrieveChatAsync(
            [FromQuery, Required] string chatId,
            [FromQuery, Required] string conversationId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(chatId))
                {
                    return BadRequest(new { error = "ChatId不能为空" });
                }

                if (string.IsNullOrWhiteSpace(conversationId))
                {
                    return BadRequest(new { error = "ConversationId不能为空" });
                }

                _logger.LogInformation($"收到查询聊天记录请求，ChatId: {chatId}, ConversationId: {conversationId}");

                var request = new ChatRetrieveRequestDto
                {
                    ChatId = chatId,
                    ConversationId = conversationId
                };

                var result = await _kouziAIService.RetrieveChatAsync(request);

                if (result.Success)
                {
                    _logger.LogInformation($"聊天记录查询成功，状态: {result.Status}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"聊天记录查询失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询聊天记录时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 提交工具执行结果给扣子AI智能体
        /// </summary>
        /// <param name="request">工具执行结果提交请求</param>
        /// <returns>工具结果提交响应</returns>
        /// <response code="200">提交成功，返回处理结果</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("submit-tool-outputs")]
        [ProducesResponseType(typeof(SubmitToolOutputsResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<SubmitToolOutputsResponseDto>> SubmitToolOutputsAsync([FromBody] SubmitToolOutputsRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到工具结果提交请求，ChatId: {request.ChatId}, 工具数量: {request.ToolOutputs?.Count ?? 0}");

                var result = await _kouziAIService.SubmitToolOutputsAsync(request);

                if (result.Success)
                {
                    _logger.LogInformation($"工具结果提交成功，状态: {result.Status}");
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning($"工具结果提交失败: {result.ErrorMessage}");
                    return StatusCode(StatusCodes.Status500InternalServerError, result);
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex, "请求参数无效");
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提交工具结果时发生未预期的错误");
                return StatusCode(StatusCodes.Status500InternalServerError, 
                    new { error = "服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 检查扣子AI服务健康状态
        /// </summary>
        /// <returns>true表示服务正常，false表示服务异常</returns>
        /// <response code="200">健康检查成功</response>
        /// <response code="503">服务不可用</response>
        [HttpGet("health-check")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
        public async Task<ActionResult<bool>> HealthCheckAsync()
        {
            try
            {
                _logger.LogInformation("收到健康检查请求");

                var isHealthy = await _kouziAIService.HealthCheckAsync();

                if (isHealthy)
                {
                    _logger.LogInformation("健康检查通过");
                    return Ok(true);
                }
                else
                {
                    _logger.LogWarning("健康检查失败");
                    return StatusCode(StatusCodes.Status503ServiceUnavailable, false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "健康检查时发生错误");
                return StatusCode(StatusCodes.Status503ServiceUnavailable, false);
            }
        }
    }
}
